package com.chookss.home.myTest;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chookss.tools.NavigationTools;
import com.google.gson.reflect.TypeToken;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.TestDetailEntity;
import com.chookss.tiku.AnswerExamActivity;
import com.chookss.tiku.SimulateTestActivity;
import com.chookss.tiku.entity.MyExam;
import com.chookss.tiku.entity.Subject;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;

import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import per.wsj.library.AndRatingBar;

public class MyTestsDetailActivity extends BaseAct {

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.tvTestName)
    TextView tvTestName;
    @BindView(R.id.tvLength)
    TextView tvLength;
    @BindView(R.id.tvSocre)
    TextView tvSocre;
    @BindView(R.id.tvSubjectNum)
    TextView tvSubjectNum;
    @BindView(R.id.ratingBar)
    AndRatingBar ratingBar;
    @BindView(R.id.tvMultipleChoice)
    TextView tvMultipleChoice;
    @BindView(R.id.tvMultiSelect)
    TextView tvMultiSelect;
    @BindView(R.id.tvJudge)
    TextView tvJudge;
    @BindView(R.id.tvFill)
    TextView tvFill;
    @BindView(R.id.tvAsk)
    TextView tvAsk;
    @BindView(R.id.llMultipleChoice)
    LinearLayout llMultipleChoice;
    @BindView(R.id.llMultiSelect)
    LinearLayout llMultiSelect;
    @BindView(R.id.llJudge)
    LinearLayout llJudge;
    @BindView(R.id.llFill)
    LinearLayout llFill;
    @BindView(R.id.llAsk)
    LinearLayout llAsk;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.loadingTv)
    TextView loadingTv;
    @BindView(R.id.loading_view_progressbar)
    ProgressBar loading_view_progressbar;
    @BindView(R.id.loadingIv)
    ImageView loadingIv;
    @BindView(R.id.loadingTvInit)
    TextView loadingTvInit;
    @BindView(R.id.llProgress)
    LinearLayout llProgress;
    @BindView(R.id.llMiddle)
    LinearLayout llMiddle;
    private String examCode;
    private String examStatus;
    private String recordType;
    private MyExam myExam;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_tests_detail);
        ButterKnife.bind(this);
        initState();
    }

    @Override
    public void initData() {
        examCode = getIntent().getStringExtra("examCode");
        examStatus = getIntent().getStringExtra("examStatus");
        recordType = getIntent().getStringExtra("recordType");
        NavigationTools.saveUseRecord(this,"1","05");
        commonTitleTxt.setText("考试");
        if ("101".equals(examStatus)) {
            tvSure.setText("等待考试");
            llMiddle.setBackgroundResource(R.drawable.shape_main_color_18_6f);
        } else {
            tvSure.setText("开始考试");
            llMiddle.setBackgroundResource(R.drawable.shape_main_color_18);
        }
            myExam = (MyExam) getIntent().getSerializableExtra("exam");
        tvSure.setVisibility(View.VISIBLE);
        llProgress.setVisibility(View.GONE);
        showLoading();
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("examCode", examCode);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<TestDetailEntity>>() {
        }.getType(), null, Urls.getExamAnswerSheet, SignUtils2.makeSignStr(map), false, new ObserverCallback<TestDetailEntity>() {
            @Override
            public void onSuccess(TestDetailEntity data) {
                dismissLoading();
                if (tvTestName==null) {
                    return;
                }
                tvTestName.setText(data.getExamName());
                tvLength.setText(data.getExamTimeLength() + "");
                tvSubjectNum.setText(data.getTotalNum() + "道");
                tvSocre.setText(Utils.changeNumber(data.getTotalScore()) + "");
                ratingBar.setNumStars(5);
                if (Utils.isNull(data.getAvgHard())) {
                    ratingBar.setRating(0);
                } else {
                    ratingBar.setRating(Float.parseFloat(data.getAvgHard()));
                }
                if (Utils.isNull(data.getSingleNum())) {
                    llMultipleChoice.setVisibility(View.GONE);
                } else {
                    llMultipleChoice.setVisibility(View.VISIBLE);
                    tvMultipleChoice.setText("单项选择题共" + data.getSingleNum() + "题，每题" + Utils.changeNumber(data.getSingleScore()) + "分，每题的备选项中只有一个最符合题意。");
                }
                if (Utils.isNull(data.getCheckboxNum())) {
                    llMultiSelect.setVisibility(View.GONE);
                } else {
                    llMultiSelect.setVisibility(View.VISIBLE);
                    tvMultiSelect.setText("多项选择题共" + data.getCheckboxNum() + "题，每题" + Utils.changeNumber(data.getCheckboxScore()) + "分，每题的备选项中有2个或2个以上符合题意。错选，本题不得分。");
                }
                if (Utils.isNull(data.getJudgeNum())) {
                    llJudge.setVisibility(View.GONE);
                } else {
                    llJudge.setVisibility(View.VISIBLE);
                    tvJudge.setText("判断题共" + data.getSingleNum() + "题，每题" + Utils.changeNumber(data.getSingleScore()) + "分，每题的备选项中只有一个最符合题意。");
                }
                if (Utils.isNull(data.getFillNum())) {
                    llFill.setVisibility(View.GONE);
                } else {
                    llFill.setVisibility(View.VISIBLE);
                    tvFill.setText("填空题共" + data.getFillNum() + "题，每题" + Utils.changeNumber(data.getFillScore()) + "分，答案命中得分点得相应分值，命中所有得分点得"+Utils.changeNumber(data.getFillScore()) + "分。");
                }
                if (Utils.isNull(data.getAskNum())) {
                    llAsk.setVisibility(View.GONE);
                } else {
                    llAsk.setVisibility(View.VISIBLE);
                    tvAsk.setText("问答题共" + data.getAskNum() + "题，每题" + Utils.changeNumber(data.getAskScore()) + "分，答对得相应分值，完全答对得"+Utils.changeNumber(data.getAskScore()) + "分。");
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getExamData() {
        Map<String, String> map = new HashMap<>();
        map.put("examCode", examCode);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<Subject>>>() {
        }.getType(), null, Urls.getPaperSubject, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<Subject>>() {
            @Override
            public void onSuccess(List<Subject> data) {
                isHaveExam = true;
                //缓存卷子题目
                XJson.setDataList(MyTestsDetailActivity.this, examCode, data);
                //清空卷子答题情况
                new ShareUtils().putString(MyTestsDetailActivity.this, examCode+"_answer","");
                //清空卷子答题下标
                new ShareUtils().putInt(MyTestsDetailActivity.this, examCode+"_index",0);

                if (millisecond >= 1000) {
                    close();
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void close() {
        if (loading_view_progressbar==null) {
            return;
        }
        loading_view_progressbar.setVisibility(View.GONE);
        loadingIv.setVisibility(View.VISIBLE);
        loadingTvInit.setText("创建成功");
        loadingTv.setText("100%");
        if ("3".equals(recordType)) {
            Intent intent = new Intent(MyTestsDetailActivity.this, SimulateTestActivity.class);
            intent.putExtra("answerType", "2");
            intent.putExtra("recordType", recordType);
            intent.putExtra("exam", myExam);
            startActivity(intent);
        } else {
            Intent intent = new Intent(MyTestsDetailActivity.this, AnswerExamActivity.class);
            intent.putExtra("answerType", "1");
            intent.putExtra("exam", myExam);
            intent.putExtra("recordType", recordType);
            startActivity(intent);
        }
        finish();
    }

    @OnClick({R.id.common_title_back, R.id.tvSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (tvSure==null) {
                    return;
                }
                if ("3".equals(recordType)) {
                    startTimer();
                    tvSure.setVisibility(View.GONE);
                    llProgress.setVisibility(View.VISIBLE);
                    getExamData();
                } else {
                    if (tvSure.getText().toString().equals("等待考试")) {
                        MyToast.show("考试时间未到");
                    } else {
                        startTimer();
                        tvSure.setVisibility(View.GONE);
                        llProgress.setVisibility(View.VISIBLE);
                        getExamData();
                    }
                }

                break;
        }
    }

    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private boolean isHaveExam = false; //是否获取了考试信息
    private int allTime = 0;//百分比进度条
    private int millisecond = 0;//创建考场所用的毫秒数，最少1s

    private void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //每分中上传数据
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            };
        }
        if (mTimer != null && mTimerTask != null) {
            mTimer.schedule(mTimerTask, 200, 200);//执行定时器中的任务
        }
    }

    // handler类接收数据
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                allTime++;
                millisecond = millisecond + 200;
                if(isHaveExam){
                    if (millisecond >= 1000) {
                        stopTimer();
                       close();
                    } else {
                        if (loadingTv != null) {
                            loadingTv.setText((allTime * 10) + "%");
                        }
                    }
                }else{
                    if (allTime >= 10) {
                        if (loadingTv != null) {
                            loadingTv.setText("99%");
                        }
                        stopTimer();
                    } else {
                        if (loadingTv != null) {
                            loadingTv.setText((allTime * 10) + "%");
                        }

                    }
                }
            }
        }

    };

    /**
     * 停止定时器，初始化定时器开关
     */
    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }
}
